<template>
  <el-dialog
    :title="isAdd ? '新增文件' : '修改文件'"
    v-model="open"
    width="500px"
    append-to-body
    @close="cancel"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="文档名称" prop="docName">
        <el-input v-model="form.docName" placeholder="请输入文档名称" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="文件" prop="fileUpload">
        <el-upload
          style="width: 100%"
          ref="uploadRef"
          :file-list="fileList"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          :on-change="onChange"
          limit="1"
          :on-exceed="handleExceed"
          :auto-upload="false"
        >
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">限制上传一个xlxs文件</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, toRefs, defineEmits } from "vue";
import { useStore } from "vuex";
import { addSource, updateSource } from "@/api/system/datasource.js";
import { ElMessage } from "element-plus";

const props = defineProps({
  isAdd: {
    type: Boolean,
    default: true,
  },
});
const emit = defineEmits(["refresh"]);
const store = useStore();
let open = ref(false);
// 初始化表单
let form = reactive({
  docName: "",
  uploadTime: "",
  operator: "",
  remark: "",
});
const formRef = ref(null);
const uploadRef = ref();
// 重置表单备份
const resetForm = reactive({ ...form });
// 表单校验
let rules = reactive({
  docName: [{ required: true, message: "文档名称不能为空", trigger: "blur" }],
});
let fileList = reactive([]);
/** 取消 */
const cancel = () => {
  reset();
  open.value = false;
};
/** 重置 */
const reset = () => {
  Object.assign(form, resetForm);
};
/** 提交 */
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      form.operator = store.state.user.name;
      let date = new Date();
      form.uploadTime = [
        date.getFullYear(),
        date.getMonth() + 1,
        date.getDate(),
      ].join("-");
      //触发成功验证表单，调用接口；
      if (props.isAdd) {
        // addSource(form).then((res) => {
        //   ElMessage({
        //     message: "新增成功",
        //     type: "success",
        //   });
        //   emit("refresh");
        //   cancel();
        // });
        cancel();
      } else {
        // updateSource(form).then((res) => {
        //   ElMessage({
        //     message: "修改成功",
        //     type: "success",
        //   });
        //   emit("refresh");
        //   cancel();
        // });
        cancel();
      }
    }
  });
};
/** 文件上传钩子函数 */
const beforeUpload = (file, fileList) => {
  const validExtensions = [".xlsx", ".xls"];
  const extension = file.name.slice(file.name.lastIndexOf("."));

  if (!validExtensions.includes(extension)) {
    ElMessage({
      message: "文件格式不正确",
      type: "warning",
    });
    return false;
  }
  return true;
};
const onChange = (file) => {
  const validExtensions = [".xlsx", ".xls"];
  const extension = file.name.slice(file.name.lastIndexOf("."));
  if (!validExtensions.includes(extension)) {
    ElMessage({
      message: "文件格式不正确",
      type: "warning",
    });
    fileList = [];
    uploadRef.value.clearFiles();
  } else {
    fileList.push(file);
  }
};
const handleExceed = (files, fileList) => {
  fileList[0].row = files[0];
  fileList[0].name = files[0].name;
  uploadRef.value.clearFiles();
  uploadRef.value.handleStart(files[0]);
};

defineExpose({
  open,
  form,
});
</script>
